﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.Diagnostics;
using System.Web.Security;
using CCF20.Properties;

namespace CCF20
{
    /// <summary>
    /// Interaction logic for UserManager.xaml
    /// </summary>
    public partial class UserManager : UserControl
    {
        public UserManager()
        {
            InitializeComponent();
        }
        private void ShowError(Exception ex)
        {
            //ErrorDetailWindow.BuildErrorDetailWindow(this, ex).ShowDialog();
            throw (ex);
            //MessageBox.Show(ex.Message);
        }

        #region Role Management

        private void RefreshRoleTree()
        {
            mainTreeView.Items.Clear();

            TreeViewItem rootItem = new TreeViewItem()
            {
                Header = Properties.Resources.Role_All
            };
            rootItem.Selected += new RoutedEventHandler(RootItem_Selected);

            
            String[] allRoles = Roles.GetAllRoles();
                foreach (String r in allRoles)
                {
                    TreeViewItem tvi = new TreeViewItem()
                    {
                        Header = r
                    };
                    tvi.Selected += new RoutedEventHandler(TreeViewItem_Selected);
                    rootItem.Items.Add(tvi);
                }
            mainTreeView.Items.Add(rootItem);

            rootItem.IsExpanded = true;
        }

        private IEnumerator<String> EnumerateAllUsers()
        {
            MembershipUserCollection allUsers = Membership.GetAllUsers();
            foreach (MembershipUser u in allUsers)
            {
                yield return u.UserName;
            }
        }

        private IEnumerator<String> EnumerateRole(String roleName)
        {
            if (Roles.RoleExists(roleName))
            {
                String[] users = Roles.GetUsersInRole(roleName);
                foreach (String u in users)
                {
                    yield return u;
                }
            }
        }

        private void ShowUserResults(IEnumerator<String> userResults)
        {
            this.resultsListView.Items.Clear();
            while (userResults.MoveNext())
            {
                ListViewItem lvi = new ListViewItem()
                {
                    Content = userResults.Current
                };

                lvi.MouseDoubleClick += new MouseButtonEventHandler(ListViewItem_MouseDoubleClick);

                this.resultsListView.Items.Add(lvi);
            }
        }

        void ListViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                ListViewItem doubleClickedItem = e.Source as ListViewItem;
                if (doubleClickedItem != null)
                {
                    String username = doubleClickedItem.Content as String;
                    if (username != null)
                    {
                        MembershipUser doubleClickedUser = Membership.GetUser(username);
                        if (doubleClickedUser != null)
                        {
                            UserDetailsWindow userDetails = this.BuildOwnedWindowWithTitle<UserDetailsWindow>(doubleClickedUser.UserName);
                            userDetails.DisplayedUser = doubleClickedUser;
                            userDetails.Show();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
        }

        private void CreateRole(String roleName)
        {
            Roles.CreateRole(roleName);
            RefreshRoleTree();
        }

        private void RemoveRole(String roleName)
        {
            Roles.DeleteRole(roleName);
            RefreshRoleTree();
        }

        #endregion

        internal T BuildOwnedWindowWithTitle<T>(String title)
            where T: Window, new()
        {
            T detailsWindow = new T();
            detailsWindow.Owner = Window.GetWindow(this);
            detailsWindow.Title = title;
            return detailsWindow;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            RefreshRoleTree();
        }

        private void RootItem_Selected(object sender, RoutedEventArgs e)
        {
            try
            {
                IEnumerator<String> userEnum = EnumerateAllUsers();
                ShowUserResults(userEnum);
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
        }

        private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            try
            {
                TreeViewItem tvi = e.Source as TreeViewItem;
                if (tvi != null)
                {
                    String roleName = tvi.Header.ToString();
                    IEnumerator<String> userEnum = EnumerateRole(roleName);
                    ShowUserResults(userEnum);
                }

                e.Handled = true;
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
        }

        private void AddRole_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                DialogWindow dlg = this.BuildOwnedWindowWithTitle<DialogWindow>(Properties.Resources.Role_Add);
                dlg.SetDisplayValues(Properties.Resources.Role_Label, String.Empty);
                bool? dlgResult = dlg.ShowDialog();

                if (dlgResult.HasValue && dlgResult.Value)
                {
                    String roleName = dlg.textBox1.Text;
                    CreateRole(roleName);
                }
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
        }

        private void RemoveRole_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                String defaultRoleName = GetSelectedRoleName();

                DialogWindow dlg = this.BuildOwnedWindowWithTitle<DialogWindow>(Properties.Resources.Role_Remove);
                dlg.SetDisplayValues(Properties.Resources.Role_Label, defaultRoleName);
                bool? dlgResult = dlg.ShowDialog();

                if (dlgResult.HasValue && dlgResult.Value)
                {
                    String roleName = dlg.textBox1.Text;
                    RemoveRole(roleName);
                }
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
        }

        private String GetSelectedRoleName()
        {
            TreeViewItem tvi = mainTreeView.SelectedItem as TreeViewItem;
            String defaultRoleName = (tvi != null) ? tvi.Header.ToString() : String.Empty;
            return defaultRoleName;
        }

        private void AddUser_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                UserCreateWindow newUserDetails = BuildOwnedWindowWithTitle<UserCreateWindow>(Properties.Resources.User_Add);
                newUserDetails.ShowDialog();
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
        }

        private void RemoveUser_MenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ListViewItem selectedItem = this.resultsListView.SelectedItem as ListViewItem;
                if (selectedItem != null)
                {
                    String selectedUsername = selectedItem.Content as string;
                    bool userSuccessfullyDeleted = Membership.DeleteUser(selectedUsername);

                    if (userSuccessfullyDeleted)
                    {
                        this.resultsListView.Items.Remove(selectedItem);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError(ex);
            }
        }

        private void RoleDetail_Clicked(object sender, RoutedEventArgs e)
        {
            TreeViewItem selectedItem = mainTreeView.SelectedItem as TreeViewItem;
            if (null == selectedItem)
                return;
            RoleDetail roleDetail = new RoleDetail(selectedItem.Header.ToString());
            roleDetail.CurrentRoleName.Text = string.Format("当前{0}分组权限：",selectedItem.Header.ToString());
            roleDetail.ShowDialog();
        }

 }
}
